<template>
  <div class="discount">
    <div class="discount-title">贴现</div>
    <div class="discount-item">
      <el-form
        ref="formRef"
        :inline="true"
        :model="discount"
        class="demo-form-inline"
        label-position="top"
        size="default"
        :rules="discountRules"
        @keyup.enter="handleDiscountEnter"
        @click.stop
      >
        <!-- 表单字段 -->
        <el-form-item label="承兑人信息" prop="acceptor">
          <el-input ref="firstInput" v-model="discount.acceptor" style="width: 120px" />
        </el-form-item>
        <el-form-item label="票面金额(万元)" prop="billAmount">
          <el-input
            v-model="discount.billAmount"
            placeholder=""
            style="width: 120px"
            @input="handleInput('billAmount')"
          />
        </el-form-item>
        <el-form-item label="点数" prop="points">
          <el-input
            v-model="discount.points"
            placeholder=""
            style="width: 80px"
            @input="handleInput('points')"
          />
        </el-form-item>
        <el-form-item label="张数" prop="open">
          <el-select v-model="discount.open" placeholder="" style="width: 80px">
            <el-option v-for="number in 10" :key="number" :label="number" :value="number" />
          </el-select>
        </el-form-item>
        <el-form-item style="display: flex; align-items: flex-end">
          <el-button
            v-if="!isEditBoolendis"
            type="primary"
            @click="onSubmit(formRef, 'discountList')"
            >添加</el-button
          >
          <el-button v-else type="primary" @click="doEdit('discount')">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
// 1. 引入 storeToRefs
import { storeToRefs } from 'pinia'
import type { FormInstance, FormRules } from 'element-plus'
import { inputFormat, dealWith, dealWithEdit } from './utils/from'
import { tableDataStoreHook } from '@store/dataStore'
import { useScrollStoreHook } from '@store/scrollStore' // 引入滚动 store

const tableDataStore = tableDataStoreHook()
const scrollStore = useScrollStoreHook() // 获取滚动 store

// 2. 使用 storeToRefs 替换 computed [3,6](@ref)
const { discount, isEditBoolendis } = storeToRefs(tableDataStore)

interface RuleForm {
  acceptor: string
  billAmount: string
  points: string
  open: string
}

const discountRules = reactive<FormRules<RuleForm>>({
  acceptor: [{ required: true, message: '请输入承兑人信息', trigger: 'blur' }],
  billAmount: [{ required: true, message: '请输入票面金额（万元）', trigger: 'blur' }],
  points: [{ required: true, message: '请输入点数', trigger: 'blur' }],
  open: [
    {
      required: true,
      message: '请选择张数',
      trigger: 'change'
    }
  ]
})

interface DiscountItem {
  serialNumber: number
  matter: string
  acceptor: string
  billAmount: string
  points: string
  open: number
  rebate: string
  interestDeduction: string
  checked?: boolean
}
const formRef = ref<FormInstance>()
const firstInput = ref<HTMLInputElement>()
const item = ref<DiscountItem>({
  serialNumber: 1,
  matter: '',
  acceptor: '',
  billAmount: '',
  points: '',
  open: 1,
  rebate: '',
  interestDeduction: ''
})

// 3. 访问 discount.value 属性（已是 Ref 对象）
const handleInput = (field: string) => {
  console.log(discount.value[field])
  discount.value[field] = inputFormat(field, discount.value)
}

const handleDiscountEnter = () => {
  if (isEditBoolendis.value) {
    // 4. 直接使用 .value 访问
    doEdit('discount')
  } else {
    onSubmit(formRef.value, 'discountList')
  }
}

// ========== 关键修改：添加触发滚动函数 ==========
// #region 公共提交方法
const onSubmit = async (formEl: FormInstance | undefined, type: string) => {
  if (!formEl) return

  try {
    // 1. 先进行表单验证
    await formEl.validate()

    // 2. 处理业务逻辑
    const result = await dealWith(type, discount.value)
    if (result) {
      // 3. 提交数据到store
      tableDataStore.doSubmit(result, 'discountList')

      // 4. 重置表单
      formEl.resetFields()
      firstInput.value?.focus()

      // 5. 触发滚动到最新行（在nextTick中确保DOM已更新）
      nextTick(() => {
        scrollStore.triggerScroll('discountList')
      })
    }
  } catch (error) {
    // 验证失败处理
    console.error('表单验证失败:', error)
  }
}
// #endregion

// #region 公共修改方法
// 列表选中表单修改
const doEdit = async (type: string) => {
  if (!formRef.value) return

  try {
    // 1. 先进行表单验证
    await formRef.value.validate()

    // 2. 处理业务逻辑
    const result = await dealWithEdit(type, discount.value, item.value)

    if (result) {
      // 3. 更新数据到store
      tableDataStore.doUpdate(result, 'discountList')

      // 4. 重置表单
      formRef.value.resetFields()
      firstInput.value?.focus()

      // 5. 触发滚动（如果需要）
      nextTick(() => {
        scrollStore.triggerScroll('discountList')
      })
    }
  } catch (error) {
    // 验证失败处理
    console.error('表单验证失败:', error)
  }
}
// #endregion

// ComponentB（监听通知）
watch(
  () => tableDataStore.currentItemType,
  (newMsgs) => {
    if (newMsgs !== null && newMsgs == 'discount') {
      console.log('discount', newMsgs)
    }
  }
)
</script>

<style lang="scss" scoped>
.discount {
  width: 100%;
  height: 100%;
  // margin: 12px 0;
  padding: 12px;
  // background: #f8f9fa;
  // border-radius: 8px;
  // border: 1px solid #ccc;
  // padding: 20px;
  .discount-title {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 10px;
  }
  .discount-item {
    display: flex;
    width: 100%;
    height: 100%;
  }
}
</style>
